package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Table;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {


    @Autowired
    SendEmailCallback sendEmailCallback;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;



    private final String ORDER_GLOBAL_ID_CACHE_KEY="ORDER_ID";
    private final String ORDER_ITEM_GLOBAL_ID_CACHE_KEY="ORDER_ITEM_ID";
    @Override
    public TransCallback getTransCallback() {
        return sendEmailCallback;
    }

    @Override
    public boolean isAsync() {
        return false;
    }

    @Transactional
    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        // 创建订单
        Order order = new Order();
        String orderId = globalIdGeneratorUtil.getNextSeq(ORDER_GLOBAL_ID_CACHE_KEY, 1);
        order.setOrderId(orderId);
        order.setUserId(createOrderContext.getUserId());
        order.setPayment(createOrderContext.getOrderTotal());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setBuyerNick(createOrderContext.getBuyerNickName());
        int rows = orderMapper.insertSelective(order);
        if(rows != 1){
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(), OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }

        // 插入订单商品关联表
        List<CartProductDto> productDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto productDto : productDtoList) {
            OrderItem orderItem = new OrderItem();
            String orderItemId = globalIdGeneratorUtil.getNextSeq(ORDER_ITEM_GLOBAL_ID_CACHE_KEY, 1);

            orderItem.setOrderId(orderId);
            orderItem.setId(orderItemId);
            orderItem.setItemId(productDto.getProductId());
            orderItem.setStatus(1);
            orderItem.setTitle(productDto.getProductName());
            Double price = productDto.getSalePrice().doubleValue();
            orderItem.setPrice(price);
            Integer num = productDto.getProductNum().intValue();
            orderItem.setNum(num);
            Double totalFee = price * num;
            orderItem.setTotalFee(totalFee);
            orderItem.setPicPath(productDto.getProductImg());

            int affectedRows = orderItemMapper.insertSelective(orderItem);
            if(affectedRows != 1){
                throw new BizException("订单商品关联表插入失败！");
            }
        }

        createOrderContext.setOrderId(orderId);
        return true;
    }

}
